package thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-14
 * Time：15:03
 */
public class Demo1 {
    //CAS操作:伪代码
    //    boolean CAS(address, expectValue, swapValue) {
    //        if (&address == expectedValue) {
    //                &address = swapValue;
    //                return true;
    //        }
    //        return false;
    //    }

    //    private int value;
    //    public int getAndIncrement() {
    //    int oldValue = value;//oldValue看作一个寄存器
    //    //CAS是一个指令-原子操作
    //    while (CAS(value, oldValue, oldValue+1) != true) {
    //            oldValue = value;
    //        }
    //        return oldValue;
    //    }

    //CAS实现自旋锁
    //    public class SpinLock{
    //        private Thread owner = null;
    //
    //        while(CAS(owner, null, Thread.currentThread()) != true)
    //    }
    public static AtomicInteger count = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count.getAndIncrement();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count.getAndIncrement();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}
